package com.quanshu.exchange;

import android.content.Intent;
import android.os.Bundle;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.quanshu.exchange.support.api.LoginInterface;
import com.quanshu.exchange.support.config.PermissionObserver;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.VersionEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.HomePageActivity;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.widget.LoadingDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import util.UpdateAppUtils;


public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Observable.timer(2000, TimeUnit.MICROSECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> requestPermissions());
    }

    private void requestPermissions() {
        new RxPermissions(this)
                .request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE)
                .subscribe(new PermissionObserver(this) {
                    @Override
                    public void onSuccess() {
                        getDownloadNewVersion();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastHelper.toast("请下载最新版本");
                    }
                });
    }

    //这个方法干啥的
    private void gotoNext() {
        UserEntity currentUser = MyApplication.getInstance().getCurrentUser();
        if (currentUser != null && currentUser.getMemberid() != null && currentUser.getMemberid().trim().length() > 0) {
            doAutoLogin(currentUser);
        } else {
            Intent intent = new Intent(MainActivity.this, HomePageActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void getDownloadNewVersion() {
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .getNewVersion()
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<VersionEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<VersionEntity> response) {
                        if (response.getData() != null) {
                            doChooseUpgrade(response.getData());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        gotoNext();
                    }
                });
    }

    private void doChooseUpgrade(VersionEntity entity) {
        int localCode = AppUtils.getVersionCode(this);
        if (localCode < entity.getVersion_code()) {
            String str = entity.getNew_feature().replace("\\n", "\n");
            UpdateAppUtils.from(this)
                    .checkBy(UpdateAppUtils.CHECK_BY_VERSION_NAME) //更新检测方式，默认为VersionCode
                    .serverVersionCode(entity.getVersion_code())
                    .serverVersionName(entity.getVersion_name())
                    .apkPath(entity.getApk_url())
                    .showNotification(false) //是否显示下载进度到通知栏，默认为true
                    .updateInfo(str)  //更新日志信息 String
                    .downloadBy(UpdateAppUtils.DOWNLOAD_BY_BROWSER) //下载方式：app下载、手机浏览器下载。默认app下载
                    .isForce(true) //是否强制更新，默认false 强制更新情况下用户不同意更新则不能使用app
                    .update();
        } else {
            gotoNext();
        }
    }

    private void doAutoLogin(UserEntity currentUser) {

        LoadingDialog loadingDialog = new LoadingDialog(MainActivity.this, false);
        loadingDialog.show();
        doLoginEase(currentUser, loadingDialog);
    }

    private void doLoginEase(UserEntity entity, final LoadingDialog loadingDialog) {

        EMClient.getInstance().login(entity.getMemberid(), "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    Intent intent = new Intent(MainActivity.this, HomePageActivity.class);
                    startActivity(intent);
                    finish();
                });
            }

            @Override
            public void onError(int code, String error) {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
//                    if (code == USER_ALREADY_LOGIN) {
//                        EMClient.getInstance().groupManager().loadAllGroups();
//                        EMClient.getInstance().chatManager().loadAllConversations();
//                        Intent intent = new Intent(MainActivity.this, HomePageActivity.class);
//                        startActivity(intent);
//                        finish();
//                    } else {
                    ToastHelper.toast("登录失败=code" + code + "+error" + error);
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
//                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

}
